package com.cus.shd.sharingjdbc.config;

import org.apache.commons.lang.StringUtils;
import org.apache.shardingsphere.sharding.api.sharding.ShardingAutoTableAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Collection;

/**
 * @author ASUS
 * @Description 自定义分片策略
 * @Date 2021/11/6 22:20
 **/

public class OrderDeliveryIdShardingAlgorithm implements StandardShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        String orderDeliveryId = shardingValue.getValue().toString();
        orderDeliveryId = orderDeliveryId.substring(0,orderDeliveryId.length() - 4);
        // 将时间戳转为当前时间
        LocalDateTime localDateTime = LocalDateTime.ofEpochSecond(Long.valueOf(orderDeliveryId)/1000, 0, ZoneOffset.ofHours(8));
        String availableTargetName;
        int month = localDateTime.getMonthValue();
        LocalDateTime nowTime = LocalDateTime.now();
        int year = nowTime.getYear();
        if(month >= 1 && month < 3){
            availableTargetName = "01";
        }else if(month >= 3 && month < 6){
            availableTargetName = "02";
        }else if(month >= 6 && month < 9){
            availableTargetName = "03";
        }else {
            availableTargetName = "04";
        }
        if(StringUtils.isEmpty(availableTargetName)){
            return null;
        }
        return String.format("%s_%s%s",shardingValue.getLogicTableName(),year,availableTargetName);
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Long> shardingValue) {
        return availableTargetNames;
    }

    @Override
    public void init() {

    }

    @Override
    public String getType() {
        return "ORDER_DELIVERY_ID";
    }
}
